package com.gameco.data.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.gameco.data.service.DataAnalysisService;
import core.ApiResponse;
import dto.ParamDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vo.DataRoot;
import vo.v1.DataRoot_V1;
import vo.v2.DataRoot_V2;

/**
 * 航司控制类
 */
@RestController
@RequestMapping("/platform")
@Slf4j
public class DecryptionController {

    // 数据解析服务
    @Autowired
    private DataAnalysisService dataAnalysisService;

    // 从配置文件中获取私钥，默认值为"xxx"
    @Value("${spring.privateKey:xxx}")
    private String privateKey;

    /**
     * 数据解密接口
     * @param dto 包含加密数据的传输对象
     * @return 包含解密结果的ApiResponse
     */
    @PostMapping("/decryptData")
    public ApiResponse<String> decryptData(@RequestBody ParamDto dto) {
        return dataAnalysisService.DataAnalysis(dto.getXmlEncryptionData(),privateKey);
    }


    /**
     * 数据加密处理接口（场景二：不需要加解密的场景）
     * @param root 需要处理的数据对象
     * @return 包含处理结果的ApiResponse
     * @throws JsonProcessingException 当JSON转换失败时抛出
     */
    @PostMapping("/encrypt")
    public ApiResponse<String> encrypt(@RequestBody DataRoot root) throws JsonProcessingException {
        // 创建 ObjectMapper 并启用字段排序
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        String data = null;
        if(root.getCodeVersion().equals("0.1")){
            DataRoot_V1 root_v1 = objectMapper.convertValue(root, DataRoot_V1.class);
            // 将对象转换为 JSON 字符串
            data = objectMapper.writeValueAsString(root_v1);
        }
        if(root.getCodeVersion().equals("0.2")){
            DataRoot_V2 root_v2 = objectMapper.convertValue(root, DataRoot_V2.class);
            // 将对象转换为 JSON 字符串
            data = objectMapper.writeValueAsString(root_v2);
        }
        String codeVersion = root.getCodeVersion();
        return  dataAnalysisService.DataAnalysisWeb(data,codeVersion);
    }
}
